<template>
  <van-search v-model="searchText" placeholder="搜索好友" @search="onSearch"/>
  <friend-card-list :friend-list="friendList" :loading="loading"/>
  <van-empty v-if="!friendList || friendList.length < 1" description="暂无好友" />
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import FriendCardList from "../../components/FriendCardList.vue";
import {showToast} from "vant";
import myAxios from "../../plugins/myAxios.ts";
import {UserType} from "../../models/user";

const loading = ref(true);
const friendList = ref();
const searchText = ref('');

onMounted(async () => {
  loading.value = true;
  const res : any = await myAxios.get('/friend/list');
  if (res?.code === 0) {
    res.data.forEach((user: UserType) =>{
      if (user.tags){
        user.tags = JSON.parse(user.tags);
      }
    })
    friendList.value = res.data;
    showToast('加载成功');
  } else {
    showToast('加载失败');
  }
  loading.value = false;
});

// 搜索好友
const onSearch = async () => {
  loading.value = true;
  try {
    // 确保使用POST请求，并且请求体格式与后端DTO匹配
    const res = await myAxios.post('/friend/search', {
      searchParam: searchText.value  // 字段名必须与FriendQueryRequest中的字段名一致
    });
    
    console.log('搜索响应:', res); // 调试用
    
    if (res?.code === 0) {
      if (res.data?.length > 0) {
        res.data.forEach((user: UserType) => {
          if (user.tags) {
            user.tags = JSON.parse(user.tags);
          }
        });
        friendList.value = res.data;
        showToast(`找到${res.data.length}个好友`);
      } else {
        friendList.value = [];
        showToast('没有找到匹配的好友');
      }
    } else {
      showToast(res?.message || '搜索失败');
    }
  } catch (error: any) {
    console.error('搜索出错:', error);
    // 更详细的错误提示
    if (error.response?.status === 401) {
      showToast('请先登录');
    } else {
      showToast(error.response?.data?.message || '请求失败，请检查网络');
    }
  } finally {
    loading.value = false;
  }
};


</script>


